<template>
  <div :class="prefixCls">
    <BasicTable @register="registerTable" :rowSelection="rowSelection" v-bind="$attrs">
      <template #tableTitle>
        <a-button preIcon="ant-design:plus-outlined" type="primary" style="margin-right: 5px" @click="handleAdd">录入</a-button>

        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined" />
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作<Icon icon="mdi:chevron-down" /> </a-button>
        </a-dropdown>
      </template>

      <template #dbSync="{ text }">
        <span v-if="text === 'Y'" style="color: limegreen">已同步</span>
        <span v-if="text === 'N'" style="color: red">未同步</span>
      </template>

      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
    </BasicTable>
  </div>
  <CgreportModal @register="registerModal" @success="handleSuccess" />
</template>
<script lang="ts">
  import { defineComponent } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { list, batchDelete, getReportParam, deleteOne } from './cgreport.api';
  import { columns, searchFormSchema } from './cgreport.data';
  import CgreportModal from './components/CgreportModal.vue';
  import { useModal } from '/@/components/Modal';
  import Clipboard from 'clipboard';
  import { useRouter } from 'vue-router';
  import { buildUUID } from '/@/utils/uuid';

  export default defineComponent({
    name: 'CgreportIndex',
    components: {
      BasicTable,
      TableAction,
      CgreportModal,
    },
    setup() {
      let router = useRouter();
      const [registerModal, { openModal }] = useModal();
      const {
        prefixCls,
        tableContext,
        createMessage: $message,
        createConfirm: $confirm,
      } = useListPage({
        designScope: 'online-cgreport-list',
        pagination: true,
        tableProps: {
          title: 'Online报表',
          api: list,
          rowKey: 'id',
          columns,
          formConfig: {
            autoSubmitOnEnter: true,
            showAdvancedButton: true,
            schemas: searchFormSchema,
          },
        },
      });
      const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;
      function handleAdd() {
        openModal(true, {
          isUpdate: false,
          showFooter: true,
        });
      }
      function handleEdit(record) {
        openModal(true, {
          record,
          isUpdate: true,
          showFooter: true,
        });
      }
      async function handleDelete(record) {
        await deleteOne({ id: record.id }, reload);
      }
      async function batchHandleDelete() {
        await batchDelete({ ids: selectedRowKeys.value }, () => {
          reload();
          selectedRowKeys.value = [];
        });
      }
      function handleSuccess() {
        reload();
      }
      function getTableAction(record) {
        return [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
        ];
      }
      function getDropDownAction(record) {
        return [
          {
            label: '功能测试',
            class: ['low-app-hide'],
            onClick: () => onShowList(record.id),
          },
          {
            label: '配置地址',
            class: ['low-app-hide'],
            onClick: () => onShowOnlineUrl(record),
          },
          {
            label: '删除',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleDelete.bind(null, record),
            },
          },
        ];
      }
      function onShowList(id) {
        router.push({ path: '/online/cgreport/' + id });
      }
      function onShowOnlineUrl(record) {
        let id = record.id;
        let baseUrl = `/online/cgreport/${id}`;
        let insertMenuSql = `INSERT INTO sys_permission(id, parent_id, name, url, component, component_name, redirect, menu_type, perms, perms_type, sort_no, always_show, icon, is_route, is_leaf, keep_alive, hidden, hide_tab, description, status, id_del, rule_flag, create_by, create_time, update_by, update_time, internal_or_external) 
                         VALUES ('${buildUUID()}', NULL, '${
          record.name
        }', '${baseUrl}', '1', NULL, NULL, 0, NULL, '1', 0.00, 0, NULL, 0, 1, 0, 0, 0, NULL, '1', 0, 0, 'admin', null, NULL, NULL, 0)`;
        getReportParam(id)
          .then((arr) => {
            let urlParam = '';
            if (arr && arr.length > 0) {
              for (let i of arr) {
                urlParam += i.paramName + '=${' + i.paramName + '}&';
              }
            }
            if (urlParam.length > 0) {
              urlParam = urlParam.substring(0, urlParam.length - 1);
              baseUrl += '?' + urlParam;
            }
          })
          .catch(() => {
            $message.warning('获取参数失败!');
          })
          .finally(() => {
            $confirm({
              iconType: 'info',
              width: 500,
              title: `菜单链接【${record.name}】`,
              content: baseUrl,
              closable: true,
              maskClosable: true,
              cancelText: '复制SQL',
              okText: '复制URL',
              cancelButtonProps: {
                class: 'copy-this-sql',
                'data-clipboard-text': insertMenuSql,
              },
              okButtonProps: {
                class: 'copy-this-text',
                'data-clipboard-text': baseUrl,
              },
              onOk() {
                return new Promise((resolve) => {
                  const clipboard = new Clipboard('.copy-this-text');
                  clipboard.on('success', () => {
                    clipboard.destroy();
                    $message.success('复制成功');
                    resolve();
                  });
                  clipboard.on('error', () => {
                    $message.error('该浏览器不支持自动复制');
                    clipboard.destroy();
                    resolve();
                  });
                });
              },
              onCancel() {
                return new Promise((resolve) => {
                  const clipboard = new Clipboard('.copy-this-sql');
                  clipboard.on('success', () => {
                    clipboard.destroy();
                    $message.success('复制插入菜单SQL成功');
                    resolve();
                  });
                  clipboard.on('error', () => {
                    $message.error('该浏览器不支持自动复制');
                    clipboard.destroy();
                    resolve();
                  });
                });
              },
            });
          });
      }
      return {
        prefixCls,
        registerTable,
        rowSelection,
        selectedRowKeys,
        handleAdd,
        batchHandleDelete,
        handleSuccess,
        getTableAction,
        getDropDownAction,
        registerModal,
      };
    },
  });
</script>
